
import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';

import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';


import { Hero } from './hero';
import { HEROES } from './mock-heroes';


@Injectable()
export class HeroService {
	private headers = new Headers({ 'Content-Type': 'application/json' });
	private heroesUrl = 'app/heroes2';  // URL to web api

	constructor(private http: Http) { }

	getHeroes(): Hero[] {
		return HEROES;
	}

	getHeroesByPromise(): Promise<Hero[]> {
		return Promise.resolve(HEROES);
	}

	getHeroesSlowly(): Promise<Hero[]> {
		return new Promise<Hero[]>(resolve =>
			setTimeout(resolve, 2000)) // delay 2 seconds
			.then(() => this.getHeroes());
	}

	getHeroesByHttp(): Promise<Hero[]> {
		return this.http.get(this.heroesUrl)
			.toPromise()
			.then(response => response.json().data as Hero[])
			.catch(this.handleError);
	}
	
	getHero(id: number): Promise<Hero> {
		return this.getHeroesByPromise().then(heroes => heroes.find(hero => hero.id === id));
	}
	
	private handleError(error: any): Promise<any> {
		console.error('An error occurred', error); // for demo purposes only
		return Promise.reject(error.message || error);
	}
}

